#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include <cerrno>
#include <cstring>
#include <string>
#include <iostream>
#include <string>
class Sock
{
private:
    const static int gbacklog = 10;

public:
    Sock() {}
    ~Sock() {}

    static int Socket()
    {
        int listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (listensock < 0)
        {
            logMessage(FATAL, "create socket error,%d:%s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "create socket sucess,listensock:%d", listensock);

        int opt = 1;
        setsockopt(listensock,SOL_SOCKET,SO_REUSEADDR | SO_REUSEPORT ,&opt,sizeof opt);
        return listensock;
    }

    static void Bind(int socket, uint16_t port, std::string ip = "0.0.0.0")
    {
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &local.sin_addr);

        if (bind(socket, (sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "bind error, %d:%s", errno, strerror(errno));
            exit(3);
        }
    }

    static void Listen(int sock)
    {
        if (listen(sock, gbacklog) < 0)
        {
            logMessage(FATAL, "listen error, %d:%s", errno, strerror(errno));
            exit(4);
        }
        logMessage(NORMAL, "init server success");
    }

    static int Accept(int listensock, std::string *ip, uint16_t *port)
    {
        struct sockaddr_in local;
        socklen_t len = sizeof(local);
        int serversock = accept(listensock, (sockaddr *)&local, &len);

        if (serversock < 0)
        {
            logMessage(ERROR, "accept error, %d:%s", errno, strerror(errno));
            return -1;
        }

        if (port)
            *port = ntohs(local.sin_port);
        if (ip)
            *ip = inet_ntoa(local.sin_addr);
        return serversock;
    }

    static bool Connect(int sock, const std::string &ip, const uint16_t &port)
    {
        struct sockaddr_in server;
        memset(&server,0,sizeof server);
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(ip.c_str());
        server.sin_port = htons(port);
        
        if(connect(sock,(sockaddr*)&server,sizeof(server))==0)
            return true;
        else
            return false;
    }
};
